package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.*;
import com.dongdongshop.utils.IdWorker;
import com.dongdongshop.vo.CartVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
@Service
public class OrderServiceImpl implements OrderService {
    @DubboReference
    private CartService cartService;

    @DubboReference(check = false)
    private AddressService addressService;

    @DubboReference
    private OrderItemService orderItemService;

    @DubboReference
    private ItemService itemService;

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Override
    public void addOrder(TbOrder tbOrder) {
        tbOrderMapper.insertSelective(tbOrder);
    }

    @Transactional
    @GlobalTransactional(rollbackFor = Exception.class)//添加全局事务注解
    @Override
    public Map<String, Object> createOrder(TbUser user, List<Long> ids, String paymentType, Long addressId, String sumPic) {
//创建一个新的集合,用来存储我们选择的id的信息
        List<CartVo> cartOrder = new ArrayList<CartVo>();
        List<CartVo> cartListFormRedis = cartService.getCartListFormRedis(user.getId());
        for (Long id : ids) {
            for (CartVo cartVo : cartListFormRedis) {
                for (TbOrderItem tbOrderItem : cartVo.getCartDetailList()) {
                    if (id.equals(tbOrderItem.getItemId())){
                        cartOrder = cartService.selectItemById(cartOrder,id,tbOrderItem.getNum());
                    }
                }
            }
            //将选中的id,传过去,使数量小于0.
            cartListFormRedis = cartService.selectItemById(cartListFormRedis,id,-99);
        }
//        cartService.delCartListToRedis(user.getId());
        //将新的集合存到reids中
        cartService.addCartListToRedis(user.getId(),cartListFormRedis);


        //创建母订单号
        IdWorker idWorker = new IdWorker();
        long orderNum= idWorker.nextId();
        //创建订单的名字
        String subject = user.getUsername()+"orderName";


        //遍历我们的订单集合
        for (CartVo cartVo : cartOrder) {
            long orderId= idWorker.nextId();

            TbAddress tbAddress = addressService.selectById(addressId);

            TbOrder tbOrder = new TbOrder();
            tbOrder.setSellerId(cartVo.getSellerId());
            tbOrder.setOrderId(orderId);
            tbOrder.setUserId(user.getUsername());
            BigDecimal num1 = new BigDecimal(0);
            tbOrder.setPayment(num1);
            tbOrder.setPaymentType(paymentType);
            tbOrder.setReceiverAreaName(tbAddress.getAddress());
            tbOrder.setReceiverMobile(tbAddress.getMobile());
            tbOrder.setReceiver(tbAddress.getContact());
            tbOrder.setOrderNum(String.valueOf(orderNum));

            for (TbOrderItem tbOrderItem : cartVo.getCartDetailList()) {
                //更新库存
                TbItem item = itemService.getItemByItemId(tbOrderItem.getItemId());
                item.setStockCount(item.getStockCount() - tbOrderItem.getNum());
                if (item.getStockCount() <0){
                    throw new RuntimeException("商品库存不足");
                }
                itemService.updateStockCount(item);

                long orderItemId = idWorker.nextId();
                tbOrderItem.setId(orderItemId);
                tbOrderItem.setOrderId(orderId);
                tbOrderItem.setOrderNum(String.valueOf(orderNum));
                BigDecimal totalFee = tbOrderItem.getTotalFee();

                num1 = num1.add(totalFee);
                //将数据添加到数据库
                orderItemService.addOrderItem(tbOrderItem);
            }
            tbOrderMapper.insertSelective(tbOrder);
        }

        Map<String,Object> map = new HashMap<>();
        String s = String.valueOf(orderNum);
        map.put("orderNum",s);
        map.put("subject",subject);
        map.put("sumPrice",sumPic);

        return map;
    }

    @Override
    public void updateAllOrder(String out_trade_no, String trade_no) {
        tbOrderMapper.updateAllOrder(out_trade_no,trade_no);
    }

    @Override
    public List<TbOrder> selectOrderByUserId(String userId) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo("2");
        criteria.andUserIdEqualTo(userId);

        return tbOrderMapper.selectByExample(example);
    }

    @Override
    public TbOrder selectOrderByOrederNum(String orderNum) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNumEqualTo(orderNum);
        List<TbOrder> orders = tbOrderMapper.selectByExample(example);
        return (orders.size()>0)?orders.get(0):new TbOrder();
    }
}
